-- MonsterBuilding
-- Created by cheny3 Jun/03/2016
-- 刷怪建筑

-- 内部函数声明
local doTransElement;

-- 初始化
function initMonsterBuilding(self)
    local pos = self.gridData:getPos();
    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    if not buildingInfo then
        error("获取不到建筑查看配置，元素类型：" .. class);
        return;
    end

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            if self.gridData.type ~= GRID_TYPE_MONSTER_BUILDING then
                -- 格子已经被转换
                return;
            end

            -- 如果在副本中，需要清怪以后才能拾取奖励
            if DungeonInstanceM.isInInstance() and
               not DungeonM.isAllMonsterDead() then
                self:openBuildingView(nil, nil, buildingInfo["dialog2"], getLocStr("btn_text_leave"));
                return;
            end

            local function okFunc()
                if not self.gridData.bonus then
                    -- 没有奖励
                    return;
                end

                if self.gridData.brave_vs_dragon == 1 then
                    -- 勇者斗恶龙
                    DungeonActionM.go("brave_building_bonus", self.gridData:getPos());
                    -- 需要转换格子
                    if self.gridData.trans_element then
                        doTransElement(self);
                    end
                else
                    DungeonActionM.go("do_building_bonus", self.gridData:getPos());
                end
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            -- 音效
            AudioM.playFx("ui_open1");

            -- 打开建筑查看界面
            self:openBuildingView(okFunc);
        end
    end

    -- 建筑图标
    local iconPath = getLevelItemIconPath(buildingInfo["icon"]);

    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);
    self.iconPath = iconPath;
end

function doTransElement(self)
    -- 转换格子
    DungeonActionM.go("element_transform", self.gridData:getPos());
    -- 原本cd隐藏掉
    local cdNode = findChildByName(self.node, "cd_node");
    cdNode:setVisible(false);
end
